package com.lm.paymentadmin.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author liu2dog
 * redis分布式锁
 */
@Slf4j
@Component
public class RedisLock {
    /**
     * 锁键
     */
    private String lock_key = "redis_lock";

    /**
     * 锁过期时间
     */
    private long internalLockLeaseTime = 30;

    private static final Long SUCCESS = 1L;

    /**
     * 获取锁最长时间
     */
    private long timeout = 90000;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public boolean lock(String value) {
        Long start = System.currentTimeMillis();
        try {
            for (; ; ) {
                //SET命令返回OK ，则证明获取锁成功
                Boolean ret = redisTemplate.opsForValue().setIfAbsent(lock_key, value, internalLockLeaseTime, TimeUnit.SECONDS);
                if (ret) {
                    return true;
                }
                //否则循环等待，在timeout时间内仍未获取到锁，则获取失败
                long end = System.currentTimeMillis() - start;
                if (end >= timeout) {
                    return false;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } finally {

        }
    }
    /**
     * 解锁
     * @param value
     * @return
     */
    public Boolean unlock( String value) {
        //lua脚本保证原子性
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);
        Object result = redisTemplate.execute(redisScript, Collections.singletonList(lock_key),value);
        if(SUCCESS.equals(result)) {
            return true;
        }

        return false;
    }

    /**
     * 创建线程给锁续命
     * @param value
     * @return
     */
     public Thread createLifeThread(String value){
        return new Thread(()->{
           while (true){
               try {
                   TimeUnit.SECONDS.sleep(internalLockLeaseTime*2/3);
                   //lua脚本保证原子性
                   String script = "if redis.call('get', KEYS[1]) == ARGV[1] " +
                       "then return redis.call('expire', KEYS[1],ARGV[2]) else return 0 end";
                   RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);
                   Object result = redisTemplate.execute(redisScript, Collections.singletonList(lock_key),value,internalLockLeaseTime);
               } catch (Exception e) {
                   e.printStackTrace();
                   return;
               }
           }
        });
     }

}
